<template>
  <view class="ai-generate-container">
    <!-- <view class="dialog-box">
      <text class="dialog-title">AI 对话</text>
      <scroll-view scroll-y class="dialog-messages">
        <view v-for="(m, i) in messages" :key="i" :class="['msg', m.role]">
          <text>{{ m.content }}</text>
        </view>
      </scroll-view>
    </view> -->

    <view class="result-box">
      <text class="result-title">AI文案生成</text>
      <textarea class="result-text" v-model="result" placeholder="生成内容将显示在这里" auto-height></textarea>
    </view>

    <view class="footer-actions">
      <button class="gen-btn" :loading="loading" @tap="onGenerate">点击生成</button>
      <button class="back-btn" @tap="onBack">返回</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      product: null,
      messages: [],
      result: '',
      loading: false
    }
  },
  onLoad() {
    try {
      const payload = uni.getStorageSync('ai_product_payload')
      if (payload) {
        this.product = payload
        this.initMessages(payload)
      } else {
        uni.showToast({ title: '无产品数据', icon: 'none' })
      }
    } catch (e) {
      uni.showToast({ title: '读取数据失败', icon: 'none' })
    }
  },
  methods: {
    initMessages(p) {
      const formatPercentage = (val) => parseFloat(((val || 0) * 100).toFixed(2))
      const summary = `产品：${p.productName}\n价格：${p.productPrice}\n佣金：${p.productBack}（比例:${formatPercentage(p.productProfit)}%）\n销量：${p?.stats?.sales || 0} 评价：${p?.stats?.review || 0}`
      this.messages = [
        { role: 'system', content: '你是电商文案助手，请基于商品生成吸引力强的短文案，风格为抖音风格。' },
        { role: 'user', content: `${summary}\n请生成适合社交平台的推广文案，含卖点、适合人群、行动号召，字数约80-120。` }
      ]
    },
    onBack() {
      uni.navigateBack()
    },
    async onGenerate() {
      if (!this.product) {
        uni.showToast({ title: '缺少商品数据', icon: 'none' })
        return
      }
      const app = getApp?.()
      const apiKey = app?.globalData?.config?.deepseek?.apiKey || 'sk-0c52f3d78cd64e4f8e536abb5794161c'
      const endpoint = app?.globalData?.config?.deepseek?.endpoint || 'https://api.deepseek.com/chat/completions'
      if (!apiKey) {
        uni.showToast({ title: '请配置deepseek apiKey', icon: 'none' })
        return
      }
      this.loading = true
      try {
        const prompt = this.messages.map(m => `${m.role.toUpperCase()}: ${m.content}`).join('\n')
        await this.callDeepseek(endpoint, apiKey, prompt)
      } catch (e) {
        console.error(e)
        uni.showToast({ title: '生成失败', icon: 'none' })
      } finally {
        this.loading = false
      }
    },
    callDeepseek(endpoint, apiKey, prompt) {
      return new Promise((resolve, reject) => {
        uni.request({
          url: endpoint,
          method: 'POST',
          header: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${apiKey}`
          },
          data: {
            model: 'deepseek-chat',
            messages: [
              { role: 'system', content: '你是电商文案助手。' },
              { role: 'user', content: prompt }
            ],
            temperature: 0.7
          },
          success: (res) => {
            try {
              const text = res?.data?.choices?.[0]?.message?.content || ''
              this.result = text
              this.messages.push({ role: 'assistant', content: text })
              resolve(text)
            } catch (e) {
              reject(e)
            }
          },
          fail: (err) => reject(err)
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.ai-generate-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #fff;
}
.dialog-box {
  padding: 12px 12px 0;
}
.dialog-title {
  font-weight: bold;
  font-size: 16px;
  color: #333;
}
.dialog-messages {
  max-height: 36vh;
  padding: 8px;
  margin-top: 6px;
  background: #f7f7f7;
  border-radius: 8px;
}
.msg { margin-bottom: 6px; color: #333; font-size: 14px; }
.msg.system { color: #666; }
.msg.user { color: #111; }
.msg.assistant { color: #0a7; }

.result-box { padding: 12px; }
.result-title { font-weight: bold; font-size: 16px; color: #333; }
.result-text { width: 100%; min-height: 28vh; background: #fafafa; border-radius: 8px; padding: 10px; }

.footer-actions { padding: 12px; display: flex; gap: 10px; }
.gen-btn { flex: 1; background: #07c160; color: #fff; border-radius: 8px; }
.back-btn { width: 100px; background: #9ca3af; color: #fff; border-radius: 8px; }
</style>
